<?php

namespace App\Http\Controllers\Admin;

// 引入auth门面
use Auth;
use App\Http\Requests\LoginRequest;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
	/**
	 * 登录页面
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function login() {
		// 如果已登录，跳转到后台首页
		if (auth()->check()) return redirect()->route('admin.index.index');
		return view('admin.login.index');
	}

	/**
	 * 登录验证
	 * @param LoginRequest $request
	 * @return \Illuminate\Http\RedirectResponse
	 */
	public function loginSave(LoginRequest $request) {
		// 经典验证
		/*$obj = new User();
		// 调用model方法验证用户名密码是否正确
		$res = $obj->login($request->all());
		if ($res) {
			return redirect()->route('admin.index.index');
		}
		return redirect()->back()->with('msg', '账号或密码错误！');*/

		// Auth验证
		//$res = Auth::attempt($request->only(['username','password']));
		$res = auth()->attempt($request->only(['username', 'password']));
		// 记住密码
		//$res = auth()->attempt($request->only(['username', 'password']),true);
		if ($res) {
			// 记录ip
			User::find(auth()->id())->update(['ip' => $request->ip()]);
			// 如果有online，则将username加入cookie
			if ($request->has('online')) {
				$username = $request->get('username');
				$c = cookie('username', $username, 60 * 24 * 7);
				// 用auth登录自动写入session
				return redirect()->intended(route('admin.index.index'))->withCookie($c);
			}
			return redirect()->intended(route('admin.index.index'));
		}
		return redirect()->back()->with(['status' => 0, 'msg' => '账号或密码错误']);
	}

	/**
	 * 安全退出
	 * @return \Illuminate\Http\RedirectResponse
	 */
	public function logout() {
		// auth退出
		auth()->logout();
		//session()->flush();
		return redirect()->route('admin.user.login')->with(['status' => 0, 'msg' => '您已安全退出！']);
	}
}
